﻿using System.ComponentModel;
using Loki;
using Loki.Commands;
using Loki.UI;
using Luna.Model;
using Luna.Model.Security;

namespace Luna.UI
{
    public class LogonViewModel : ViewModel<LunaModel>
    {
        #region Properties
        #region  Login
        private static PropertyChangedEventArgs _LoginChangeArgs = ObservableHelper.CreateArgs<LogonViewModel>(x => x.Login);

        private string _Login;

        public string Login
        {
            get
            {
                return _Login;
            }

            set
            {
                if (value != _Login)
                {
                    _Login = value;
                    NotifyChanged(_LoginChangeArgs);
                }
            }
        }
        #endregion

        #region  Password
        private static PropertyChangedEventArgs _PasswordChangeArgs = ObservableHelper.CreateArgs<LogonViewModel>(x => x.Password);

        private string _Password;

        public string Password
        {
            get
            {
                return _Password;
            }

            set
            {
                if (value != _Password)
                {
                    _Password = value;
                    NotifyChanged(_PasswordChangeArgs);
                }
            }
        }
        #endregion
        #endregion

        public LogonViewModel()
        {
            Logon = Commands.Create();
            Cancel = Commands.Create();

            Commands.Handle(Logon, Logon_CanExecute, Logon_Execute);
            Commands.Handle(Cancel, Cancel_Execute);
        }

        private void Logon_CanExecute(object P_Sender, CanExecuteCommandEventArgs e)
        {
            e.CanExecute =
                 !string.IsNullOrEmpty(Login)
                && !string.IsNullOrEmpty(Password);
        }

        private void Logon_Execute(object P_Sender, CommandEventArgs e)
        {
            IUser L_User = ApplicationModel.Security.LogonUser(Login, Password);
            if (L_User != null)
            {
                ApplicationCommands.START.Execute(null);
                Close.Execute(null);
            }
            else
            {
                HandleError(Messages.UIMessages.INVALID_USER);
            }
        }

        private void Cancel_Execute(object P_Sender, CommandEventArgs e)
        {
            ApplicationCommands.EXIT.Execute(null);
        }

        #region Commands
        public ICommand Logon
        {
            get;
            private set;
        }

        public ICommand Cancel
        {
            get;
            private set;
        }
        #endregion
    }
}
